'use strict';

var mongoose = require('mongoose');
var express = require('express');
var passport = require('passport');
var auth = require('../auth.service');
var router = express.Router();
var User = mongoose.model('User');
const redis = require('../../util/redis');

router.post('/', function (req, res, next) {
    //测试环境不用验证码
    console.log('进入password');
    if (process.env.NODE_ENV !== 'test') {
        var error_msg;
        if (req.body.phone === '' || req.body.password === '') {
            error_msg = "用户名和密码不能为空.";
        }
        if (error_msg) {
            return res.status(400).send(error_msg);
        } else {
            next();
        }
    } else {
        next();
    }
}, function (req, res, next) {
    passport.authenticate('local', function (err, user, info) {
        if (err) {
            return res.status(401).send();
        }
        if (info) {
            return res.status(403).send(info);
        }
        var token = auth.signToken(user._id);
        console.log('加密',token);
        // redis.setex(token, 60 * 60 * 24 * 365, user._id); // token和用户id相关联 一年过期
        return res.status(200).json({token: token});
    })(req, res, next)
});

module.exports = router;
